package indi.zhifa.recipe.bailan.framework.web.common.filter;

import com.alibaba.fastjson2.JSON;
import indi.zhifa.recipe.bailan.framework.common.entity.dto.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;

/**
 * Description: 
 * @Copyright: Copyright (c) 2020-2028 北京华咨电力科技发展有限公司 All rights reserved.
 * @author: 褚智勇(hataksumo@163.com)
 * @date:  2022/4/19 10:29
 */
@Slf4j
public class BaseInterceptor {
    protected <T extends Annotation> boolean hasAnnotations(Object pHandler, Class<T> cls){
        if(pHandler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) pHandler;
            // 获取方法上的注解
            T requiredPermission = handlerMethod.getMethod().getAnnotation(cls);
            if(null != requiredPermission){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }

    protected void outputError(HttpServletResponse response, String pErrMsg) {
        outputError(response, HttpStatus.INTERNAL_SERVER_ERROR.value(),pErrMsg);
    }

    protected void outputError(HttpServletResponse response, Integer pCode, String pErrMsg) {
        PrintWriter writer = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            writer = response.getWriter();
            RestResponse<String> restResponse = RestResponse.error(pCode,pErrMsg);
            writer.print(JSON.toJSONString(restResponse));
        } catch (Exception ex) {
            log.debug("输出错误时发生故障", ex);
        }
    }
}
